package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.goods.NEWIPXAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sdq
 * @Date 2022/8/31 22:28
 */
@Slf4j
@Service
public class NEWPXAPIImpl implements NEWIPXAPI {
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private InterAttrMapper interAttrMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {

//        try {
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner);
            params.put("pg", "apiAddGame");
            String paramsStr = JSONObject.toJSONString(params);
            log.info(salePartner.getName() + "新增请求参数={}", paramsStr);
            String response = HttpUtils.doPostForm("http://pxapi.poxiaowy.com/api/api.php", params, null);

            log.info(salePartner.getName() + "新增返回参数={}", MapUntils.unicodeToString(response));
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                result.put("outId", String.valueOf(goodsInfoAndAttrValueDto.getId()));
            }
            result.put("req", JSONObject.toJSONString(params));
            result.put("res", response);
            result.put("msg", msg);
            return AjaxResult.success(result);
//        } catch (Exception e) {
//            throw new GlobalException(e.getMessage());
//        }
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        try {
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> params = params(goodsInfoAndAttrValueDto,salePartner);
            params.put("pg", "apiUpdGame");
            String paramsStr = JSONObject.toJSONString(params);
            log.info(salePartner.getName() + "修改请求参数={}", paramsStr);
            String response = HttpUtils.doPostForm("http://pxapi.poxiaowy.com/api/api.php", params, null);

            log.info(salePartner.getName() + "修改返回参数={}", MapUntils.unicodeToString(response));
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            result.put("req", JSONObject.toJSONString(params));
            result.put("res", response);
            result.put("msg", msg);
            return AjaxResult.success(result);
        } catch (Exception e) {
            throw new GlobalException(e.getMessage());
        }
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        try {
            Map<String, Object> result = new HashMap<>();
            Map<String, String> params = new HashMap<>();
            params.put("pg", "apiDelGame");
            params.put("userId", sa.getTwoOther());

            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(sa.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
//            String outId = String.valueOf(goodsInfoAndAttrValueDto.getId());
            ArtRec artRec = artRecs.get(0);
            params.put("game_code", artRec.getOutid());
            String sign = DigestUtils.md5Hex("game_code=" + params.get("game_code") + "&key=" + sa.getSaleKey()).toUpperCase();
            params.put("sign", sign);
            String paramsStr = "pg=apiDelGame&userId=" + sa.getTwoOther() + "&game_code=" + artRec.getOutid() + "&signKey=" + sign;
            log.info(sa.getName() + "删除请求参数={}", paramsStr);
            String response = HttpUtils.sendGet("http://pxapi.poxiaowy.com/api/api.php", paramsStr);

            log.info(sa.getName() + "删除返回参数={}", MapUntils.unicodeToString(response));
            JSONObject resultJson = JSONObject.parseObject(response);
            String msg = resultJson.getString("msg");
            msg = MapUntils.unicodeToString(msg);
            if (!(1 == resultJson.getInteger("code"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            artRecMapper.updateArtRec(artRec);
            result.put("req", JSONObject.toJSONString(params));
            result.put("res", response);
            result.put("msg", msg);
            return AjaxResult.success(result);
        } catch (Exception e) {
            throw new GlobalException(e.getMessage());
        }
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {

        Map<String, Object> params = new TreeMap<>();
        params.put("game_code", goodsInfoAndAttrValueDto.getId());//账号编号
        params.put("game_type", "9");//游戏类型ID（固定9）
        String campId = "1111111";


        GameAttribute gameAttribute = null;
        if (goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")) {
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
            campId = goodsInfoAndAttrValueDto.getF17();
            params.put("game_id", "10");//游戏名称ID（王者10，吃鸡11）
            params.put("inscription_num", goodsInfoAndAttrValueDto.getF13());//五级铭文数量/载具数量
            params.put("hero_num", null == goodsInfoAndAttrValueDto.getF7() || goodsInfoAndAttrValueDto.getF7().equals("") ? "0" : goodsInfoAndAttrValueDto.getF7().toString());//英雄数量/套装数量
            params.put("skin_num", null == goodsInfoAndAttrValueDto.getF8() || goodsInfoAndAttrValueDto.getF8().equals("") ? "0" : goodsInfoAndAttrValueDto.getF8().toString());//皮肤数量/枪皮数量
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("和平精英")) {
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
            campId = goodsInfoAndAttrValueDto.getF13();
            params.put("game_id", "11");//游戏名称ID（王者10，吃鸡11）
            params.put("inscription_num", null == goodsInfoAndAttrValueDto.getF7() || goodsInfoAndAttrValueDto.getF7().equals("") ? "0" : goodsInfoAndAttrValueDto.getF7());//五级铭文数量/载具数量
            params.put("hero_num", null == goodsInfoAndAttrValueDto.getF8() || goodsInfoAndAttrValueDto.getF8().equals("") ? "0" : goodsInfoAndAttrValueDto.getF8().toString());//英雄数量/套装数量
            params.put("skin_num", null == goodsInfoAndAttrValueDto.getF9() || goodsInfoAndAttrValueDto.getF9().equals("") ? "0" : goodsInfoAndAttrValueDto.getF9().toString());//皮肤数量/枪皮数量
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")) {
            params.put("game_type", "10");
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
            params.put("game_id", "7630");//游戏名称ID（王者10，吃鸡11）
            params.put("inscription_num", 0);//五级铭文数量/载具数量
            params.put("hero_num", null == goodsInfoAndAttrValueDto.getF8() || goodsInfoAndAttrValueDto.getF8().equals("") ? "0" : goodsInfoAndAttrValueDto.getF8().toString());//英雄数量/套装数量
            params.put("skin_num", null == goodsInfoAndAttrValueDto.getF9() || goodsInfoAndAttrValueDto.getF9().equals("") ? "0" : goodsInfoAndAttrValueDto.getF9().toString());//皮肤数量/枪皮数量
            if (gameAttribute.getFieldName().contains("无修改机会且实名不是本人")) {
                params.put("ercixiugai", "N");
            }
            if (gameAttribute.getFieldName().contains("有修改机会")) {
                params.put("ercixiugai", "Y");
            }
            if (gameAttribute.getFieldName().contains("无修改机会且实名是本人")) {
                params.put("ercixiugai", "B");
            }
            if (gameAttribute.getFieldName().contains("已删实名")) {
                params.put("ercixiugai", "C");
            }
            JSONObject jsonObject = JSONObject.parseObject(LCConstant.pxcfdaqu);
            String data = jsonObject.getString("data");
            JSONArray jsonArray = JSONArray.parseArray(data);
            for (Object o : jsonArray) {
                if (goodsInfoAndAttrValueDto.getServerName().equals(JSONObject.parseObject(o.toString()).getString("serverName"))) {
                    params.put("game_account_type", JSONObject.parseObject(o.toString()).getString("serverId"));//账号类型（1 QQ 2 微信）
                    params.put("is_system", JSONObject.parseObject(o.toString()).getString("id"));//操作系统（1 安卓 2 苹果）
                }
            }
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("原神")) {
            params.put("game_type", "9");
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
            params.put("game_id", "5679");//游戏名称ID（王者10，吃鸡11）
            params.put("inscription_num", goodsInfoAndAttrValueDto.getF7() == null || goodsInfoAndAttrValueDto.getF7().equals("") ? "0" : goodsInfoAndAttrValueDto.getF7());//五级铭文数量/载具数量
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF11())) {
                params.put("hero_num", goodsInfoAndAttrValueDto.getF11().split(",").length);
                params.put("skin_num", goodsInfoAndAttrValueDto.getF11().split(",").length);
            } else {
                params.put("hero_num", 0);
                params.put("skin_num", 0);
            }
            if (gameAttribute.getFieldName().equals("未绑定邮箱")) {
                params.put("ercixiugai", "5768");
            } else if (gameAttribute.getFieldName().contains("未实名")) {
                params.put("ercixiugai", "5767");
            } else if (gameAttribute.getFieldName().contains("已实名")) {
                params.put("ercixiugai", "5766");
            } else if (gameAttribute.getFieldName().equals("不送邮箱/死邮")) {
                params.put("ercixiugai", "5769");
            } else {
                params.put("ercixiugai", "8788");
            }
            params.put("game_account_type", "0");
            if (goodsInfoAndAttrValueDto.getCarrierName().equals("游戏官方")) {
                params.put("is_system", "3");
            } else if (goodsInfoAndAttrValueDto.getSystemName().equals("苹果")) {
                params.put("is_system", "4");
            }
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")) {
            params.put("game_type", "9");
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
            params.put("game_id", "8052");//游戏名称ID（王者10，吃鸡11）
            params.put("inscription_num", 0);//五级铭文数量/载具数量
            params.put("hero_num", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF5()) ? goodsInfoAndAttrValueDto.getF5() : 0);
            params.put("skin_num", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF4()) ? goodsInfoAndAttrValueDto.getF4() : 0);
            if (gameAttribute.getFieldName().equals("无修改人脸机会/实名是本人")) {
                params.put("ercixiugai", "B");
            } else if (gameAttribute.getFieldName().equals("有修改人脸机会/实名是本人")) {
                params.put("ercixiugai", "Y");
            } else {
                params.put("ercixiugai", "B");
            }
            if (goodsInfoAndAttrValueDto.getCarrierName().endsWith("Q")) {
                params.put("game_account_type", "1");//账号类型（1 QQ 2 微信）
            } else {
                params.put("game_account_type", "2");//账号类型（1 QQ 2 微信）
            }
            if (goodsInfoAndAttrValueDto.getSystemName().equals("安卓")) {
                params.put("is_system", "1");
            } else if (goodsInfoAndAttrValueDto.getSystemName().equals("苹果")) {
                params.put("is_system", "2");
            }
        }
        else if (goodsInfoAndAttrValueDto.getGameName().contains("火影忍者")) {
            params.put("game_type", "9");
            GameAttribute gzAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF7()));
            params.put("game_id", "7290");//游戏名称ID（王者10，吃鸡11）
            params.put("inscription_num", 0);
            params.put("hero_num", 0);//英雄数量/套装数量
            params.put("skin_num", 0);//皮肤数量/枪皮数量
            if (gameAttribute.getFieldName().contains("可改二次")) {
                params.put("ercixiugai", "Y");
            } else if (gameAttribute.getFieldName().contains("不可二次")) {
                params.put("ercixiugai", "N");
            } else if (gameAttribute.getFieldName().contains("已删实名")) {
                params.put("ercixiugai", "C");
            } else {
                params.put("ercixiugai", "B");
            }
            if (goodsInfoAndAttrValueDto.getCarrierName().endsWith("Q")) {
                params.put("game_account_type", "1");//账号类型（1 QQ 2 微信）
            } else {
                params.put("game_account_type", "2");//账号类型（1 QQ 2 微信）
            }
            if (goodsInfoAndAttrValueDto.getSystemName().startsWith("安卓")) {
                params.put("is_system", "1");//操作系统（1 安卓 2 苹果）
            } else {
                params.put("is_system", "2");//操作系统（1 安卓 2 苹果）
            }
            params.put("game_region", goodsInfoAndAttrValueDto.getGroupName() == null || goodsInfoAndAttrValueDto.getGroupName().equals("") ? "1" : goodsInfoAndAttrValueDto.getGroupName());
        }
        else if (goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")) {
            params.put("game_type", "8");
            params.put("game_id", "5509");
            params.put("inscription_num", 0);
            params.put("hero_num", 0);//英雄数量/套装数量
            params.put("skin_num", 0);//皮肤数量/枪皮数量
            params.put("ercixiugai", "Y");
            if (goodsInfoAndAttrValueDto.getGroupName().contains("网易")) {
                params.put("game_account_type", "5604");
                params.put("is_system", "5604");
            } else {
                params.put("game_account_type", "5605");
                params.put("is_system", "5605");
            }
        }
        else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")) {
            params.put("game_type", "8");
            params.put("game_id", "8682");
            params.put("inscription_num", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF5()) ? goodsInfoAndAttrValueDto.getF5() : "0");
            params.put("hero_num", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF3()) ? goodsInfoAndAttrValueDto.getF3() : "0");
            params.put("skin_num", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF4()) ? goodsInfoAndAttrValueDto.getF4() : "0");
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF1())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
                if (gameAttribute1.getFieldName().contains("有修改人脸机会")) {
                    params.put("ercixiugai", "Y");
                } else if (gameAttribute1.getFieldName().equals("无修改人脸机会/实名是本人")) {
                    params.put("ercixiugai", "B");
                } else if (gameAttribute1.getFieldName().equals("无修改人脸机会/实名不是本人")) {
                    params.put("ercixiugai", "N");
                } else {
                    params.put("ercixiugai", "C");
                }
            } else {
                params.put("ercixiugai", "N");
            }
            String string = "[{\"title\":\"电信大区\",\"id\":\"8683\",\"childrens\":[{\"title\":\"祖安\",\"id\":\"8688\"},{\"title\":\"皮城警备\",\"id\":\"8705\"},{\"title\":\"卡拉曼达\",\"id\":\"8704\"},{\"title\":\"征服之海\",\"id\":\"8703\"},{\"title\":\"守望之海\",\"id\":\"8702\"},{\"title\":\"影流\",\"id\":\"8701\"},{\"title\":\"均衡教派\",\"id\":\"8700\"},{\"title\":\"水晶之痕\",\"id\":\"8699\"},{\"title\":\"钢铁烈阳\",\"id\":\"8698\"},{\"title\":\"暗影岛\",\"id\":\"8697\"},{\"title\":\"黑色玫瑰\",\"id\":\"8696\"},{\"title\":\"裁决之地\",\"id\":\"8695\"},{\"title\":\"雷瑟守备\",\"id\":\"8694\"},{\"title\":\"巨神峰\",\"id\":\"8693\"},{\"title\":\"战争学院\",\"id\":\"8692\"},{\"title\":\"皮尔特沃夫\",\"id\":\"8691\"},{\"title\":\"班德尔城\",\"id\":\"8690\"},{\"title\":\"诺克萨斯\",\"id\":\"8689\"},{\"title\":\"艾欧尼亚\",\"id\":\"8687\"},{\"title\":\"云顶之巅\",\"id\":\"12519\"}]},{\"title\":\"网通大区\",\"id\":\"8684\",\"childrens\":[{\"title\":\"比尔吉沃特\",\"id\":\"8707\"},{\"title\":\"德玛西亚\",\"id\":\"8708\"},{\"title\":\"弗雷尔卓德\",\"id\":\"8709\"},{\"title\":\"无畏先锋\",\"id\":\"8710\"},{\"title\":\"恕瑞玛\",\"id\":\"8711\"},{\"title\":\"扭曲丛林\",\"id\":\"8712\"},{\"title\":\"巨龙之巢\",\"id\":\"8713\"}]},{\"title\":\"峡谷之巅\",\"id\":\"8685\",\"childrens\":[{\"title\":\"峡谷之巅\",\"id\":\"8714\"}]},{\"title\":\"男爵领域\",\"id\":\"8686\",\"childrens\":[{\"title\":\"男爵领域\",\"id\":\"8715\"}]}]\n";
            JSONArray jsonArray = JSONArray.parseArray(string);
            for (Object o : jsonArray) {
                String childrens = JSONObject.parseObject(o.toString()).getString("childrens");
                JSONArray jsonArray1 = JSONArray.parseArray(childrens);
                for (Object p : jsonArray1) {
                    if (goodsInfoAndAttrValueDto.getServerName().equals(JSONObject.parseObject(p.toString()).getString("title"))) {
                        params.put("game_account_type", JSONObject.parseObject(p.toString()).getString("id"));//账号类型（1 QQ 2 微信）
                        params.put("is_system", JSONObject.parseObject(o.toString()).getString("id"));//操作系统（1 安卓 2 苹果）
                        break;
                    }
                }
            }
        }
        else {
            throw new GlobalException("暂不支持此游戏");
        }
        params.put("camp_id", campId);//营地号

        params.put("account_number", createQQAccount());
        String attrData = "";



        params.put("attrData", "");
        if("王者荣耀，和平精英".contains(goodsInfoAndAttrValueDto.getGameName())) {
            if (gameAttribute.getFieldName().equals("不可二次实名")) {
                params.put("ercixiugai", "N");
            }else if (gameAttribute.getFieldName().equals("可二次实名")) {
                params.put("ercixiugai", "Y");
            }else if (gameAttribute.getFieldName().equals("包人脸")) {
                params.put("ercixiugai", "B");
            }else if (gameAttribute.getFieldName().equals("已删实名")) {
                params.put("ercixiugai", "C");
            }
        }else if("穿越火线".contains(goodsInfoAndAttrValueDto.getGameName())){
            if (gameAttribute.getFieldName().equals("无修改机会且实名不是本人")) {
                params.put("ercixiugai", "N");
            }else if (gameAttribute.getFieldName().contains("有修改机会")) {
                params.put("ercixiugai", "Y");
            }else if (gameAttribute.getFieldName().equals("无修改机会且实名是本人")) {
                params.put("ercixiugai", "B");
            }else {
                params.put("ercixiugai", "C");
            }
        }
        params.put("title", goodsInfoAndAttrValueDto.getDes().replace("+",""));
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgs = "";
        if (Objects.nonNull(goodsInfoAndAttrValueDto.getTitleImg())){
            imgs = goodsInfoAndAttrValueDto.getTitleImg() + ",";
        }
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = imgs + infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        } else {
            imgs =  imgs + LCConstant.defaultImg;
        }
        if (StringUtils.isNotEmpty(imgs)) {
            params.put("images", imgs + ",");
        } else {
            params.put("images", null);
        }
        params.put("game_img", goodsInfoAndAttrValueDto.getTitleImg());

        if("王者荣耀，和平精英".contains(goodsInfoAndAttrValueDto.getGameName())) {
            if (goodsInfoAndAttrValueDto.getCarrierName().endsWith("Q")) {
                params.put("game_account_type", "1");//账号类型（1 QQ 2 微信）
            } else {
                params.put("game_account_type", "2");//账号类型（1 QQ 2 微信）
            }
            if (goodsInfoAndAttrValueDto.getSystemName().startsWith("安卓")) {
                params.put("is_system", "1");//操作系统（1 安卓 2 苹果）
            } else {
                params.put("is_system", "2");//操作系统（1 安卓 2 苹果）
            }
        }
        params.put("game_region", goodsInfoAndAttrValueDto.getGroupName() == null || goodsInfoAndAttrValueDto.getGroupName().equals("") ? "1" : goodsInfoAndAttrValueDto.getGroupName());//游戏大区

        params.put("game_sell_price", goodsInfoAndAttrValueDto.getPrice().toPlainString());//销售价
//        //1王者荣耀; 2原神; 3和平精英;4吃鸡
//        if("王者荣耀".equals(goodsInfoAndAttrValueDto.getType())){
//
//        }else if("和平精英".equals(accountInfo.getType())){
//
//        }
        //以上 计算key
        String str = getCover1(params) + "key=" + salePartner.getSaleKey();
        log.info("加密前请求参数={}", str);
        String sign = DigestUtils.md5Hex(str).toUpperCase();
        params.put("signKey", sign);
        Property(goodsInfoAndAttrValueDto,params,salePartner);

        if (goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                String level = "";
                if (gameAttribute1.getFieldName().contains("无") || gameAttribute1.getFieldName().contains("V1") || gameAttribute1.getFieldName().contains("V2") || gameAttribute1.getFieldName().contains("V3")) {
                    level = "8070";
                } else if (gameAttribute1.getFieldName().contains("V4")) {
                    level = "8071";
                } else if (gameAttribute1.getFieldName().contains("V5")) {
                    level = "8072";
                } else {
                    level = "8073";
                }
                params.put("level", level);
            } else {
                params.put("level", "8070");
            }
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                String string = "[{\"title\":\"坚韧黑铁\",\"id\":\"9273\"},{\"title\":\"英勇黄铜\",\"id\":\"9274\"},{\"title\":\"不屈白银\",\"id\":\"9275\"},{\"title\":\"荣耀黄金\",\"id\":\"9276\"},{\"title\":\"华贵铂金\",\"id\":\"9277\"},{\"title\":\"璀璨钻石\",\"id\":\"10678\"},{\"title\":\"超凡大师\",\"id\":\"9278\"},{\"title\":\"傲世宗师\",\"id\":\"9279\"},{\"title\":\"最强王者\",\"id\":\"9280\"}]\n";
                JSONArray jsonArray = JSONArray.parseArray(string);
                for (Object o : jsonArray) {
                    if (JSONObject.parseObject(o.toString()).getString("title").contains(gameAttribute1.getFieldName().replace("未定级","黑铁"))) {
                        params.put("level", JSONObject.parseObject(o.toString()).getString("id"));
                        break;
                    }
                }
            } else {
                params.put("level", "9273");
            }

            params.put("is_paiwei", "7697");
        } else {
            params.put("level", "8070");
        }
        if (goodsInfoAndAttrValueDto.getGameName().equals("和平精英")) {
            params.put("amethyst_coin", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF11()) ? goodsInfoAndAttrValueDto.getF11() : 0);
            params.put("noble_points", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF12()) ? goodsInfoAndAttrValueDto.getF12() : 0);
        } else if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")) {
            params.put("noble_points", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF18()) ? goodsInfoAndAttrValueDto.getF18() : 0);
            params.put("lucky_value", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF19()) ? goodsInfoAndAttrValueDto.getF19() : 0);
            params.put("game_Imprint", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF20()) ? goodsInfoAndAttrValueDto.getF20() : 0);
        }
        if (goodsInfoAndAttrValueDto.getGameName().equals("王者荣耀")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                String string = "[{\"title\":\"V1\",\"id\":\"4772\"},{\"title\":\"V2\",\"id\":\"4773\"},{\"title\":\"V3\",\"id\":\"4774\"},{\"title\":\"V4\",\"id\":\"4775\"},{\"title\":\"V5\",\"id\":\"4776\"},{\"title\":\"V6\",\"id\":\"4777\"},{\"title\":\"V7\",\"id\":\"4778\"},{\"title\":\"V8\",\"id\":\"4779\"},{\"title\":\"V9\",\"id\":\"5159\"},{\"title\":\"V10\",\"id\":\"5160\"}]\n";
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                JSONArray jsonArray = JSONArray.parseArray(string);
                for (Object o : jsonArray) {
                    if (JSONObject.parseObject(o.toString()).getString("title").equals(gameAttribute1.getFieldName())) {
                        params.put("levenId", JSONObject.parseObject(o.toString()).getString("id"));
                        break;
                    }
                }
            } else {
                params.put("levenId", "4772");
            }
        }
        params.put("is_paiwei", "7697");
        params.put("userId", salePartner.getTwoOther());
        return params;
    }

    public static String createQQAccount() {
        int num = 8;
        String[] vec = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        num = num <= 0 ? 1 : num;
        StringBuffer str = new StringBuffer(10);
        for (int i = 0; i < num; i++) {
            int r1 = Long.valueOf(Math.round(Math.random() * (vec.length - 1))).intValue();
            str.append(vec[r1]);
        }
        return str.toString();
    }

    //参数
    private Map Property(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, SalePartner salePartner) {

        String substring = salePartner.getSaleName();
        if (substring.contains("_")) {
            substring = substring.substring(salePartner.getSaleName().indexOf("_") + 1);
        }
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        String checkAttr = interAttr.getCheckAttr();
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, params, checkAttr);

        return params;
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String checkAttr) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        String newAttrData = "";
        for (JSONObject object : checkJsonList) {
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {

                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

//                        List<String> list2 = new ArrayList<>();
//                        for (String s : split2) {
//                            s = s.replace(" ", "");
//                            list2.add(s);
//                        }
                        Object o = null;
                        try {
                            o = declaredField.get(goodsInfoAndAttrValueDto);
                        } catch (IllegalAccessException e) {
                            throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                        }
                        String oneValue = String.valueOf(o);
                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                        //开始匹配二级属性
                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                        /**
                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                         */
                        for (JSONObject jsonObject1 : jsonObjects2) {
                            String[] split1 = oneValue.split(",");
                            String ydConfigId1 = jsonObject1.getString("YdConfigId");
                            for (String s : split1) {
                                if(goodsInfoAndAttrValueDto.getGameName().equals("原神")) {
                                    GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(s));
                                    s = gameAttribute1.getParentId().toString();
                                }
                                if (Objects.equals(s, ydConfigId1)) {
                                    String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                    newAttrData+=","+InterConfigId2;
                                }
                            }
                        }
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(newAttrData)) {
            params.put("newAttrData", newAttrData.substring(1).trim());
        }else {
            params.put("newAttrData", "无");
        }
    }


    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }


    public static String getCover(Map<String, Object> params) {
        StringBuffer resut = new StringBuffer();
        for (String key : params.keySet()) {
            if (params.get(key) instanceof String && StringUtils.isNotEmpty((String) params.get(key))) {
                resut.append(key + "=" + params.get(key) + "&");
            }
            if (params.get(key) instanceof Boolean) {
                resut.append(key + "=" + params.get(key) + "&");
            }
            if (params.get(key) instanceof Long) {
                resut.append(key + "=" + params.get(key) + "&");
            }
            if (params.get(key) instanceof Integer && null != params.get(key)) {
                resut.append(key + "=" + params.get(key) + "&");
            }
        }
        return resut.toString();
    }

    public static String getCover1(Map<String, Object> params) {
        StringBuffer resut = new StringBuffer();
        for (String key : params.keySet()) {
//            if(params.get(key) instanceof String){
//                resut.append(key+"="+params.get(key)+"&");
//            }
//            if(params.get(key) instanceof Boolean){
//                resut.append(key+"="+params.get(key)+"&");
//            }
//            if(params.get(key) instanceof Long){
//                resut.append(key+"="+params.get(key)+"&");
//            }
//            if(params.get(key) instanceof Integer && null != params.get(key)){
//                resut.append(key+"="+params.get(key)+"&");
//            }
            resut.append(key + "=" + params.get(key) + "&");
        }
        return resut.toString();
    }

    public static void main(String[] args) {

        String response = getAtta(10);

        System.out.println(MapUntils.unicodeToString(response));
    }

    static String getAtta(int gameId) {
        String url = "http://pxapi.poxiaowy.com/api/api.php?pg=getGameId";

        Map<String, Object> params = new TreeMap<>();
        params.put("pg", "getGameId");
        params.put("gameId", gameId);
        String str = getCover1(params) + "key=" + "x8logf11d6o898l83botgg105c9ky83rjoi";
        log.info("加密前请求参数={}", str);
        String sign = DigestUtils.md5Hex(str).toUpperCase();
        params.put("signKey", sign);
        String response = HttpUtils.doPostForm(url, params, null);
        return response;
    }

}
